package main

import (
	"time"
	"yundian/internel/app/dao"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/logic"
	"yundian/internel/app/models/members"
	"yundian/internel/app/models/orders"
	"yundian/internel/app/models/prices"
	"yundian/internel/pkg/dbs"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
)

func main() {
	dingo.InitViper("./configs/adm.yaml")
	dbs.NewMysqlComponent().Step()
	dbs.NewRedisComponent().Step()

	wc := logic.NewSettingLogic().GetPaySettingByTypeName("gm")
	// 查询订单中正在使用的订单
	var lists []orders.OrderModel
	global.Orm.Table("orders").
		Where("state = ?", 2).
		Where("appid = ?", wc.AppId).
		Where("order_from = ?", "weixin"). // 微信
		Where("prod_type = 1").Find(&lists)

	// 遍历正在使用中的订单 - 如果订单的使用时长已超过，则自动扣款
	for _, lst := range lists {
		//log.Println(lst.TradeNo)
		param := &request.CloseOrderReq{}
		param.DeviceSn = lst.DeviceSn
		param.TradeNo = lst.TradeNo
		param.EndTime = time.Now().Unix()
		param.ProductId = lst.ProductId
		param.Openid = lst.Openid

		if lst.Openid == "" {
			m := membermodel.New()
			global.Orm.Table("members").Where("uuid = ?", lst.MemberId).Find(m).Limit(1)
			param.Openid = m.XcxOpenid
		}
		// 判断使用时长是否超时
		useTime := param.EndTime - int64(lst.PayAt)
		ruleInfo := dao.NewPricesDao().GetPriceDetail(lst.ProductId).Unwrap().(*prices.PriceModel)

		if lst.FeeMode == 1 { // 计时
			if useTime/60 >= int64(ruleInfo.MaxTime) {
				logic.NewOrderLogic().HandleWxEndOrder(param)
			}
		} else {
			if useTime/60 >= int64(ruleInfo.UseDuration) {
				logic.NewOrderLogic().HandleWxEndOrder(param)
			}
		}
	}
}